<?php

namespace MoChat\Salesman\Action;

use Hyperf\DbConnection\Db;
use MoChat\Framework\Action\AbstractAction;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Constants\ErrorCode;

/**
 * 打卡
 * @Controller
 */
class ClockIn extends AbstractAction
{
    use ValidateSceneTrait;

    private function distance($lat1, $lon1, $lat2, $lon2, $radius = 6378.137)
    {
        $rad = floatval(M_PI / 180.0);

        $lat1 = floatval($lat1) * $rad;
        $lon1 = floatval($lon1) * $rad;
        $lat2 = floatval($lat2) * $rad;
        $lon2 = floatval($lon2) * $rad;

        $theta = $lon2 - $lon1;

        $dist = acos(sin($lat1) * sin($lat2) + cos($lat1) * cos($lat2) * cos($theta));

        if ($dist < 0) {
            $dist += M_PI;
        }
        return $dist = $dist * $radius;
    }

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     * })
     * @RequestMapping(path="/dashboard/salesman/clock", methods="POST")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $data = $this->request->all();
        $this->validated($data);
        $workEmployeeId = $user['workEmployeeId'];
        $client = Db::table('client')->where('id', $data['clientId'])->first();
        if (empty($client)) {
            throw new CommonException(ErrorCode::URI_NOT_FOUND, '客户不存在,请刷新重试');
        }
//        $juli = $this->distance($client->lat, $client->lng, $data['lat'], $data['lng']);
//
//        if ($juli > 500) {
//            throw new CommonException(ErrorCode::URI_NOT_FOUND, '距离超过500米,不能打卡');
//        }
        Db::table('clock_record')
            ->insert([
                'lng' => $data['lng'],
                'lat' => $data['lat'],
                'remark' => $data['remark']??"",
                'address' => $data['address'],
                'work_employee_id' => $workEmployeeId,
                'client_id' => $data['clientId'],
                'image' => $data['image'],
                'created_at' => date('Y-m-d H:i:s'),
            ]);
        return $data;
    }

    /**
     * 验证规则.
     */
    protected function rules(): array
    {
        return [
//            'lng' => 'required',
//            'lat' => 'required',
            'remark'=>'max:255',
            'address' => 'required',
            'clientId' => 'required|integer',
            'image' => 'required'
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    protected function messages(): array
    {
        return [
//            'lng.required' => '经度必填',
//            'lat.required' => '纬度必填',
            'remark.max' => '备注不能超过255个字符',
            'address.required' => '当前打卡位置必填',
            'clientId.required' => '客户必选',
            'clientId.integer' => '客户参数错误',
            'image.required' => '打卡图片必传',
        ];
    }
}
